package controllers.commands
{
	import com.google.maps.InfoWindowOptions;
	import com.google.maps.LatLng;
	import com.google.maps.Map;
	import com.google.maps.MapMouseEvent;
	import com.google.maps.overlays.MarkerOptions;
	import com.google.maps.styles.FillStyle;
	import com.google.maps.styles.StrokeStyle;
	
	import flash.events.Event;
	import flash.geom.Point;
	import flash.text.StyleSheet;
	import flash.text.TextFormat;
	
	import mx.core.UIComponent;
	import mx.logging.ILogger;
	
	import controllers.commands.base.ICommand;
	import controllers.managers.LocationQueryManager;
	
	import event.LocationEvent;
	
	import flashx.textLayout.formats.TextAlign;
	
	import model.context.DeviceMonitorContext;
	import model.registry.ColorTable;
	import model.vo.DeviceMarker;
	import model.vo.DeviceVO;
	
	import utils.DeviceParser;
	import utils.LogUtil;
	import utils.StringUtils;
	
	import view.panel.MapDeviceView;
	
	public class CreateBatchMarkersCommand implements ICommand
	{
		public static var NAME : String = "CreateBatchMarkersCommand.as";
		
		private var context:DeviceMonitorContext;
		private var toolTipStr : String = "查询中....";
		private var addressTextStr : String = "查询中...";
		private var locationManager:LocationQueryManager = null;
		private var currentPositionData:Object;
		private var logger:ILogger =  LogUtil.getInst().getLogger( NAME );
		
		public function CreateBatchMarkersCommand(context:DeviceMonitorContext)
		{
			this.context = context;
		}
		
		public function setContext(context:Object):void
		{
			context = DeviceMonitorContext(context);
		}
		
		public function execute():void
		{
			clearMarkers();
			createMarkers();			
		}				
		
		/**
		 *  清除marker.
		 **/
		private function clearMarkers():void
		{
			logger.info("清空监控.");
			var map:Map = this.context.map;
			map.clearOverlays();
			if ( locationManager != null )
			{
				locationManager.removeEventListener(LocationQueryManager.EVENT_UPDATE, onLocationUpdateHandler);
				locationManager.removeEventListener(LocationQueryManager.EVENT_UPDATE_ERROR, onLocationErrorHandler);
				locationManager.removeEventListener(LocationQueryManager.EVENT_SECURITY_ERROR, onSecurityErrorHandler);
			}
		}
		
		private function createMarkers():void
		{
			logger.info("创建监控.");
			var map:Map = this.context.map;
			
			var lastPos:LatLng = null;
			locationManager = new LocationQueryManager();
			locationManager.addEventListener(LocationQueryManager.EVENT_UPDATE, onLocationUpdateHandler);
			locationManager.addEventListener(LocationQueryManager.EVENT_UPDATE_ERROR, onLocationErrorHandler);
			locationManager.addEventListener(LocationQueryManager.EVENT_SECURITY_ERROR, onSecurityErrorHandler);
			
			for each(var item:DeviceVO in context.locInfoList)
			{
				//新增marker
				addMarker(item, map);
				lastPos =  item.getLatLng();
			}
			
			// 单号 : MAPER-44 ,不需要设置位置
//			if ( lastPos != null)
//			{
//				map.setCenter(lastPos);
//			}
		}
		
		/**
		 * 更新地址信息
		 **/ 
		private function onLocationUpdateHandler(evt:Event):void
		{
			addressTextStr = LocationQueryManager(evt.currentTarget).formattedAddress;
			updateToolTip();
		}
		
		/**
		 * 查询地址失败
		 **/
		private function onLocationErrorHandler(event:LocationEvent):void
		{
			addressTextStr = "地址服务器不存在...";
		}
		
		/**
		 * 安全沙箱异常
		 **/
		private function onSecurityErrorHandler(event:LocationEvent):void
		{
			addressTextStr = "安全沙箱异常...";
		}
		
		/**
		 * 根据状态显示相应的颜色
		 **/
		private function addMarker(item:DeviceVO, map:Map):void
		{
			var nickName:String =  (StringUtils.isNullEmptyString(item.nickname))?"": "("+item.nickname+")"; 
			var deviceName:String = "机码:" +  item.sn + nickName;
			var deviceIcon:MapDeviceView = new MapDeviceView();
			deviceIcon.setText(deviceName);
			
			var iconContainer:UIComponent = new UIComponent();
			iconContainer.addChild(deviceIcon);
			
			deviceName = "P     " + deviceName;
			
			var textFormat:TextFormat = new TextFormat();
			textFormat.bold = true;
			textFormat.align = TextAlign.RIGHT;
			textFormat.color = 0xFF0000;
			textFormat.leftMargin = 66;
			textFormat.align = TextAlign.LEFT;
			
			var latlng:LatLng =  item.getLatLng();
				var opObj:Object = { 
					strokeStyle:new StrokeStyle({color: ColorTable.GREY}),
					fillStyle: new FillStyle({color: ColorTable.DARK_RED, alpha: 1}),
					radius: 12,
//					icon:iconContainer,						
					hasShadow: true,
					labelFormat:textFormat,
					label: deviceName};
				
				var marker:DeviceMarker = new DeviceMarker(latlng, new MarkerOptions(opObj)); 
				marker.deviceVO = item;				
				marker.addEventListener(MapMouseEvent.ROLL_OVER, onOpenMoreInfoHandler);
				marker.addEventListener(MapMouseEvent.ROLL_OUT, function(evt:MapMouseEvent):void{
					var marker:DeviceMarker = evt.currentTarget as DeviceMarker;					
					marker.closeInfoWindow(); 
				});
				
				map.addOverlay(marker);								
				
				//打开窗体
//				updateLocationTooltip();
		}
		
		private function onOpenMoreInfoHandler(evt:MapMouseEvent):void
		{
			var marker:DeviceMarker = evt.currentTarget as DeviceMarker;
			var vo:DeviceVO = marker.deviceVO;
			var contentStr:String = "";
			
			var contentStyle:StyleSheet = new StyleSheet();
			contentStyle.setStyle("color", "#00CC00"); 
			
			var contentFormat:TextFormat = new TextFormat();
			contentFormat.size = 12;
			contentFormat.color = ColorTable.BLACK;
			
			//查询
			locationManager.query( vo.latitude + "," + vo.longitude);
			
			currentPositionData = vo;
			
			updateToolTip();
			
			marker.openInfoWindow(new InfoWindowOptions({ content:toolTipStr,
				hasShadow : false,
				hasTail : false,
				width : 250,
				hasCloseButton : true,
				tailAlign : InfoWindowOptions.ALIGN_LEFT,
				pointOffset : new Point(130,  0),
				contentFormat : contentFormat})); 
		}
		/**
		 * 创建tooltips
		 **/
		private function updateToolTip():void
		{
			if ( currentPositionData != null )
			{
				var endLatLng:LatLng = new LatLng(currentPositionData.latitude,currentPositionData.longitude);
				var infoParser : DeviceParser = new DeviceParser(currentPositionData);
				//准备备注信息
				toolTipStr  = "";
				toolTipStr += " 时间: "+Global.getTimeStrByTime(currentPositionData.dateline, true ) + " \n" ;
				toolTipStr += " 方向: "+infoParser.getDirection() + "\n" ;
				toolTipStr +=  " 时速: "+infoParser.getSpeed() + "KM/h\n" ;
				toolTipStr += " 经度: "+infoParser.getLng() + "\n" ;
				toolTipStr += " 纬度: "+infoParser.getLat() + "\n" ;
				toolTipStr += " 地址: " + addressTextStr + " \n" ;
				toolTipStr += " 状态: " + currentPositionData.status_text + "\n";
			}
		}
	}	
}